package com.tjvib.view.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.NumberPicker;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jjoe64.graphview.series.DataPoint;
import com.tjvib.R;
import com.tjvib.adapter.SensorSelectAdapter;
import com.tjvib.bean.SensorSelect;
import com.tjvib.event.ScanStatusEvent;
import com.tjvib.presenter.ZeroLabSensorPresenter;
import com.tjvib.sensor.ZeroLabSensorData;
import com.tjvib.util.LogUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.TypeConversion;
import com.tjvib.util.ZLBUSDataDecoder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ZeroLabSensorActivity extends SensorActivity<ZeroLabSensorPresenter, ZeroLabSensorData> {

    private static final int IMU_DATA = 0x01;

    public static float firstTimestamp[] = {0,0};
    public static long fir = 0;
    public static long firstTime[] = {0,0};
    private List<SensorSelect> sensorSelectList = new ArrayList<>();
    private SensorSelectAdapter adapter;


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onScanStatusEvent(ScanStatusEvent event) {
        switch (event.getStatus()) {
            case "SEND_FAILURE": //发送失败
                byte[] sendBufFail = event.getData();
                String sendFail = TypeConversion.bytes2HexString(sendBufFail, sendBufFail.length);
                LogUtil.e("发送数据失败，长度" + sendBufFail.length + "--> " + sendFail);
                break;

            case "SEND_SUCCESS":  //发送成功
                byte[] sendBufSuc = event.getData();
                String sendResult = TypeConversion.bytes2HexString(sendBufSuc, sendBufSuc.length);
                ZLBUSDataDecoder.decodeSendData(sendBufSuc);
                LogUtil.i("发送数据成功，长度" + sendBufSuc.length + "--> " + sendResult);
                break;

            case "RECEIVE_FAILURE": //接收失败
                String receiveError = event.getMsg();
                showHintDialog(receiveError);
                break;

            case "RECEIVE_SUCCESS":  //接收成功
                byte[] recBufSuc = event.getData();
                int receiveDataTypeID = ZLBUSDataDecoder.decodeDataTypeID(recBufSuc);
                if (receiveDataTypeID == IMU_DATA )
                    if (ZLBUSDataDecoder.get_imu_data_format_set())
                        LogUtil.i("RECEIVE_SUCCESS, "+receiveDataTypeID);
                break;

            case "BT_CLOSED":
                Log.d(TAG, "系统蓝牙已关闭");
                break;

            case "BT_OPENED":
                Log.d(TAG, "系统蓝牙已打开");
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.startOrBindToService();
    }

    @Override
    protected void onStop() {
        presenter.stopReadingData();
        presenter.stopService();
        super.onStop();
    }

    @Override
    String getSensorName() {
        return "ZeroLab Sensor";
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_zero_lab;
    }

    @Override
    protected boolean initView() {
        ImageView sen_iv_choose = findViewById(R.id.sen_iv_choose);
        sen_iv_choose.setOnClickListener(v -> showSensorDialog());

        sen_tv_tit = findViewById(R.id.sen_tv_tit);
        sen_tv_tit.setText("ZeroLab传感器");
        sen_tv_tit.setOnClickListener(v -> showSensorDialog());

        return true;
    }

    @Override
    protected boolean initData() {
        adapter = new SensorSelectAdapter(R.layout.item_sensor_select, this, sensorSelectList);
        firstTimestamp = new float[]{0, 0};
        firstTime = new long[]{0, 0};
        fir = System.currentTimeMillis();
        presenter.resetTimestamp();
        return true;
    }

    @Override
    protected ZeroLabSensorPresenter genPresenter() {
        return new ZeroLabSensorPresenter(this);
    }

    @Override
    void setInfoLayoutData(ZeroLabSensorData data) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        sen_tv_data = findViewById(R.id.sen_tv_data);
        sen_tv_info1 = findViewById(R.id.sen_tv_info1);
        sen_tv_data.setText(getString(
                R.string.ui_zerolab_sensor_data,
                format.format(new Date(data.localtime)),
                data.timestamp,
                data.temperature,
                data.quat[0], data.quat[1], data.quat[2], data.quat[3],
                data.acc[0], data.acc[1], data.acc[2],
                data.gyr[0], data.gyr[1], data.gyr[2],
                data.mag[0], data.mag[1], data.mag[2],
                data.linAcc[0], data.linAcc[1], data.linAcc[2],
                data.euler[0], data.euler[1], data.euler[2]));
        sen_tv_info1.setText(getString(R.string.ui_zerolab_sensor_info1,
                presenter.getImuId(), 100));
    }


    private long[] lastTime = {0,0};
    @Override
    void setImageLayoutData(ZeroLabSensorData data) {
        if(data.imuId > 2) return;
        LogUtil.w("id="+data.imuId+" presenter.getImuId()="+presenter.getImuId()+" isDrawing="+isDrawing+" data.timestamp="+data.timestamp+" switchTime="+switchTime);
        if (isDrawing && data.imuId == presenter.getImuId() && data.localtime > switchTime && data.localtime > lastTime[data.imuId-1]) {
            lastTime[data.imuId-1] = data.localtime;
            graph2LastXValue = graph2LastXValue + 1.0D;
            float[] dataToShow = new float[3];
            int i = 0;
            if (this.dataSelect == R.id.sen_rb_acc) {
                while (i < 3) {
                    dataToShow[i] = data.acc[i];
                    i += 1;
                }
            } else if (this.dataSelect == R.id.sen_rb_mag) {
                while (i < 3) {
                    dataToShow[i] = data.mag[i];
                    i += 1;
                }
            } else if (this.dataSelect == R.id.sen_rb_gyr) {
                while (i < 3) {
                    dataToShow[i] = data.gyr[i];
                    i += 1;
                }
            } else if (this.dataSelect == R.id.sen_rb_lin) {
                while (i < 3) {
                    dataToShow[i] = data.linAcc[i];
                    i += 1;
                }
            }

            if(firstTime[data.imuId-1]==0) firstTime[data.imuId-1] = data.localtime;
            float time = (data.localtime - firstTime[data.imuId-1]) / 1000f;
            LogUtil.d("id="+data.imuId+" getImuId()="+presenter.getImuId()+" loc="+data.localtime
                    +" data.timestamp="+data.timestamp+" fts="+firstTimestamp[data.imuId-1]
                    +" ft="+firstTime[data.imuId-1]+" time="+time);
            mSeries1.appendData(new DataPoint(time, dataToShow[0]), true, 50);
            mSeries2.appendData(new DataPoint(time, dataToShow[1]), true, 50);
            mSeries3.appendData(new DataPoint(time, dataToShow[2]), true, 50);

//            mSeries1.appendData(new DataPoint((data.localtime - fir)/1000f, dataToShow[0]), true, 50);
//            mSeries2.appendData(new DataPoint((data.localtime - fir)/1000f, dataToShow[1]), true, 50);
//            mSeries3.appendData(new DataPoint((data.localtime - fir)/1000f, dataToShow[2]), true, 50);
        }
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.sen_rb_acc || buttonView.getId() == R.id.sen_rb_mag
                || buttonView.getId() == R.id.sen_rb_gyr || buttonView.getId() == R.id.sen_rb_lin) {
            if (isChecked) {
                dataSelect = buttonView.getId();
                removeGraph();
                drawGraph();
            }
        } else if (buttonView.getId() == R.id.sen_cb_x) {
            if (isChecked) sen_gv_data.addSeries(mSeries1);
            else sen_gv_data.removeSeries(mSeries1);
        } else if (buttonView.getId() == R.id.sen_cb_y) {
            if (isChecked) sen_gv_data.addSeries(mSeries2);
            else sen_gv_data.removeSeries(mSeries2);
        } else if (buttonView.getId() == R.id.sen_cb_z) {
            if (isChecked) sen_gv_data.addSeries(mSeries3);
            else sen_gv_data.removeSeries(mSeries3);
        }
    }


    private void showSensorDialog() {
        Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_select, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        RecyclerView dialog_select_rv = view.findViewById(R.id.dialog_select_rv);
        dialog_select_rv.setLayoutManager(new LinearLayoutManager(this));
        dialog_select_rv.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter, view1, position) -> {
            presenter.switchSensorInfo(position);
            refreshSensorSelectList();
            LogUtil.e(presenter.getImuId() + " change to " + position);
            ToastUtil.show("切换中");
            dialog.dismiss();
        });
        dialog.show();
    }


    public void refreshSensorSelectList() {
        runOnUiThread(() -> {
            sen_tv_tit = findViewById(R.id.sen_tv_tit);
            sen_tv_tit.setText(presenter.getCurName());
            sensorSelectList.clear();
            sensorSelectList.addAll(presenter.getSensorSelectList());
            adapter.notifyDataSetChanged();
        });
    }
}